﻿package net.wangit.dev.tree;

import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.dev.LockUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;

public class TreeUI implements UnitInterceptor {

	public static final String KEY = "net.wangit.dev.tree.TreeUI.treeId";
	private static final String SQL_CONFIG = "select * from TREECONFIG where tid=?";
	private static final String SQL_ITEM = "select * from TREE where tid=? order by o";
	private static MapList root;

	public TreeUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String domain = ConsoleDomainUtil.getDomain(ac);
		String source = ac.getRequestParameter("src");
		boolean copy = !Checker.isEmpty(source);
		String treeId = copy ? source : ActionContextHelper.getRequest2Session(
				ac, "treeid", TreeUI.KEY, null);
		Unit t = (Unit) unit.getElement("t").getObject();
		String unitShowMode = t.getShowMode();
		Unit i = (Unit) unit.getElement("i").getObject();
		if (!copy && "a".equals(unitShowMode)) {
			String groupId = ac.getRequestParameter("groupid");
			t.getElement("gid").setDefaultValue(groupId);
			i.setData(root);
		} else if (t.getData() == null) {
			DB db = DBHelper.getDomainDB(domain);
			MapList configData = db.query(TreeUI.SQL_CONFIG, treeId, 2);
			MapList itemData = db.query(TreeUI.SQL_ITEM, treeId, 2);
			unit.setData(configData);
			t.setData(configData);
			i.setData(itemData);
			if (copy) {
				configData.put(0, "tid", "");
				configData.put(0, "l", "0");
			}
		}
		LockUtil.setElements(ac, t, new Object[][] { new Object[] { unit,
				"save" } });
		return unit.write(ac);
	}

	static {
		root = new MapList();
		root.put(0, "id", "root");
		root.put(0, "n", "root");
	}
}
